<?php

use think\facade\Db;
use \Firebase\JWT\JWT;

//统一成功返回
function success($msg='',$data=null){
    return json([
        'code'=>1,
        'msg'=>$msg,
        'data'=>$data
    ]);
}
//统一失败返回
function error($msg='',$data=null){
    return json([
        'code'=>0,
        'msg'=>$msg,
        'data'=>$data
    ]);
}
////生成随机字符串
//function createRandStr($length=8){
//    $str='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//    $randStr='';
//    for ($i=0;$i<$length;$i++){
//        $randStr .=$str[mt_rand(0,35)];
//    }
//    return $randStr;
//}

//生成TOKEN
function signToken($userId,$mobile){
    $data=[
        //签发人
        'iss'=>request()->domain(),
        //签发时间
        'iat'=>time(),
        //自定义数据
        'data'=>[
            'user_id'=>$userId,
            'mobile'=>$mobile,
        ]
    ];
    $key=config('app.jwt_key');
    $token= JWT::encode($data,$key,'HS256');
    return $token;
}

function checkSmsCode($mobile, $code)
{
    $code = Db::name('code')->where('mobile', $mobile)->find();
    if (!$code) {
        return false;
    }
    if ($code['code'] != $code) {
        return false;
    }
    if (time() - $code['send_time'] > 3000) { // 验证码有效期5分钟
        Db::name('code')->where('mobile', $mobile)->delete();
        return false;
    }
    Db::name('code')->where('mobile', $mobile)->delete();
    return true;
}
//发送验证码
function SendCode($mobile)
{
    \api\app\model\SmsModel::where('mobile',$mobile)->delete();
    $code = mt_rand(1111, 9999);
    $config = new \Darabonba\OpenApi\Models\Config([
        // 从阿里云获取
        'accessKeyId' => config('app.aliSms.accessKeyId'),
        'accessKeySecret' => config('app.aliSms.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new \AlibabaCloud\Tea\Utils\Utils\RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = config('app.aliSms.signName');
    // 模板CODE
    $sendSmsRequest->templateCode =  config('app.aliSms.sms');
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    $Smscode = new \api\app\model\SmsModel();
    $Smscode->mobile = $mobile;
    $Smscode->code = $code;
    $Smscode->send_time = time();
    $Smscode->save();
    if ($response->body->code == 'OK') {
        return json([
            'code' => 1,
            'msg' => '短信发送成功',
            'data' => null
        ]);
    }else{
        return json([
            'code' => 0,
            'msg' => '短信发送失败',
            'data' => null
        ]);
    }
}

function add_wallet($user_id, $money, $reason, $type = 1)
{
    // 获取用户信息
    $user = Db::name('users')->where('id', $user_id)->find();
    if (!$user) {
        throw new Exception('用户不存在');
    }

    // 计算新的余额
    $newBalance = $user['money'] + $money;

    // 更新用户余额
    Db::name('users')->where('id', $user_id)->update(['money' => $newBalance]);

    // 记录流水
    Db::name('wallet')->insert([
        'user_id' => $user_id,
        'money' => $money,
        'reason' => $reason,
        'before' => $user['money'],
        'after' => $newBalance,
        'type' => $type, // 类型：1-存储
        'create_time' => date('Y-m-d H:i:s')
    ]);

    return $newBalance;
}

function record($user_id)
{
    // 查询用户的流水记录
    $logs = Db::name('wallet')
        ->where('user_id', $user_id)
        ->order('create_time', 'desc')
        ->select();

    if (!$logs) {
        throw new Exception('没有找到流水记录');
    }

    return $logs;
}